import axios from "axios";
// import { Message, MessageBox } from "element-ui";
import db from "@/config/localstorage";
// import { Base64 } from "js-base64"

// 请求添加条件，如token
axios.interceptors.request.use(
	config => {
		console.log(config);
		const isToken =
			config.headers["X-isToken"] === false ?
			config.headers["X-isToken"] :
			true;
		const token = db.get("TOKEN", "");
		if (token && isToken) {
			config.headers.token = "Bearer " + token;
		} else {
			config.headers.token = "Bearer test";
		}
		config.headers.tenant = db.get("TENANT", "c2hhb3lhbmc=");
		config.headers["tenant"] = "c2hhb3lhbmc="; //  开发模式增加
		config.headers["Authorization"] = "Basic enVpaG91X3VpOnp1aWhvdV91aV9zZWNyZXQ="; //  开发模式增加
		config.headers["userid"] = "1307946339199352832"; //  开发模式增加
		config.headers["account"] = "wxs"; //  开发模式增加
		config.headers["name"] = "wxs"; //  开发模式增加
		config.headers["token"] = "Bearer test"; //  开发模式增加

		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

// 接口返回处理
axios.interceptors.response.use(
	response => {
		return response;
	},
	error => {
		return Promise.reject(error);
	}
);

function handleError(error, reject, opts) {
	let isAlert = opts.custom ? opts.custom["isAlert"] : true;
	isAlert = isAlert === undefined ? true : isAlert;
	if (isAlert) {
		if (error.code === "ECONNABORTED") {
			uni.showToast({
				title: '请求超时',
				type: 'error',
				icon: 'none'
			})
		} else if (error.response && error.response.data) {
			if (error.response.data.msg) {
				uni.showToast({
					title: error.response.data.msg,
					type: 'error',
					icon: 'none'
				})
			} else if (error.response.data.message) {
				uni.showToast({
					title: error.response.data.message,
					type: 'error',
					icon: 'none'
				})
			}
		} else if (error.message) {
			uni.showToast({
				title: error.message,
				type: 'error',
				icon: 'none'
			})
		}
	}
	reject(error);
}

function handleSuccess(res, resolve, opts) {
	let isAlert = opts.custom ? opts.custom["isAlert"] : true;
	isAlert = isAlert === undefined ? true : isAlert;
	if (res.data.isError) {
		// 未登录
		if (
			res.data.code === 40000 ||
			res.data.code === 40001 ||
			res.data.code === 40002 ||
			res.data.code === 40003 ||
			res.data.code === 40005 ||
			res.data.code === 40006 ||
			res.data.code === 40008
		) {
			debugger;
			// MessageBox.alert(res.data.msg, "提醒", {
			//   confirmButtonText: "确定",
			//   callback: () => {
			//     window.location.hash = "/login";
			//   }
			// });
		} else {
			if (isAlert) {
				// Message.error(res.data.msg);
			}
		}
	}
	resolve(res);
}

// http请求
const httpServer = opts => {
	// 公共参数
	const publicParams = {
		ts: Date.now()
	};

	// http默认配置
	const method = opts.method.toUpperCase();
	// baseURL
	// 开发环境： /api                 // 开发环境在 vue.config.js 中有 devServer.proxy 代理
	// 生产环境： http://IP:PORT/api   // 生产环境中 代理失效， 故需要配置绝对路径
	const httpDefaultOpts = {
		method,
		// baseUrl: 'http://demo.aisclink.com/',  //测试
		// baseUrl: 'http://jk.gdxybiotech.com/', //正式
		// baseUrl: 'http://106.52.68.106:10086/',
		url: opts.url,
		responseType: opts.responseType || "",
		timeout: 30000
	};
	if (opts["meta"]) {
		httpDefaultOpts.headers = opts["meta"];
	}

	const dataRequest = ["PUT", "POST", "PATCH"];
	if (dataRequest.includes(method)) {
		httpDefaultOpts.data = opts.data || {};
	} else {
		httpDefaultOpts.params = {
			...publicParams,
			...(opts.data || {})
		};
	}

	// formData转换
	if (opts.formData) {
		httpDefaultOpts.transformRequest = [
			data => {
				const formData = new FormData();
				if (data) {
					Object.entries(data).forEach(item => {
						formData.append(item[0], item[1]);
					});
				}
				return formData;
			}
		];
	}

	const promise = new Promise((resolve, reject) => {
		axios(httpDefaultOpts)
			.then(response => {
				handleSuccess(response, resolve, opts);
			})
			.catch(error => {
				handleError(error, reject, opts);
			});
	});
	return promise;
};

export default httpServer;
